<?php
/**
 * (jobs) 生成提货汇总数据
 */
namespace App\Jobs\Shipping;

use App\Models\Shipping\SSkuApply;
use App\Models\Shipping\SSkuTotal;
use App\Models\Shipping\SSkuTotalApply;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
class SkuApproval implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $pSkuIds;
    protected $dates;

    /**
     * SkuApproval constructor.
     * @param $pSkuIds
     * @param $dates
     */
    public function __construct($pSkuIds,$dates)
    {
        $this->pSkuIds = $pSkuIds;
        $this->dates = $dates;
    }

    /**
     * Execute the job.
     * @return void
     */
    public function handle()
    {
        $this->exeFillData($this->pSkuIds,$this->dates);
    }

    private function exeFillData($pSkuIds,$dates){
        foreach ($pSkuIds as $pSkuId){
            //提货汇总
            SSkuTotal::query()->firstOrCreate(['psku_id' => $pSkuId]);
            foreach($dates as $date => $label){
                //提货汇总日期
                $sta = SSkuTotalApply::query()->firstOrNew([
                    'psku_id' => $pSkuId,
                    'shipping_date' => $date
                ]);
                $sta->apply_num = $this->_getApplyNum($pSkuId,$date); //总审批数量
                $sta->save();
            }
        }
    }

    /**
     * 获取总审批数量
     * @param $pSkuId
     * @param $date
     * @return mixed
     */
    private function _getApplyNum($pSkuId,$date){
        return SSkuApply::query()
            ->where('psku_id',$pSkuId)
            ->where('shipping_date',$date)
            ->sum('approval_num');
    }
}
